import 'dart:async';

import 'package:get/get.dart';
import 'package:xuance/bean/AiWarningitemBean.dart';
import 'package:xuance/bean/GlobalType.dart';
import 'package:xuance/bean/ReceiveDatabean.dart';
import 'package:xuance/bean/ext.dart';
import 'package:xuance/bean/global_event_bean.dart';
import 'package:xuance/main.dart';
import 'package:xuance/network/api/AiWarningApi.dart';
import 'package:xuance/util/common_util.dart';
import 'package:xuance/util/toast_util.dart';

import 'state.dart';

class HomeLogic extends GetxController {
  final HomeState state = HomeState();
  var aiWarningListPage = 1.obs;

  StreamSubscription<GlobalEventBean>? listener;
  @override
  void onInit() {
    super.onInit();
    listener = eventBus.on<GlobalEventBean>().listen((event) {
      if (event.type == GlobalType.updateDate) {
        var bean = event.data as ReceiveDataBean;
        state.dateType.value = bean.time;
        state.queryCondition.value = bean.txt;
        init();
      }
    });
    init();
  }

  Future<void> init() async {
    var time = getTime(state.dateType.value);
    try {
      var aiPredict = await AiWarningApi.aiPredice(
          startTime: time[0],
          endTime: time[1],
          queryCondition: state.queryCondition.value);
      state.aiWarnChart.clear();
      state.aiWarnChart.addAll(aiPredict);
    } catch (e) {
      print("aiWarnList加载失败:${e}");
    }
    getList(time);

    try {
      state.typeCount.clear();
      state.typeCount.addAll(await AiWarningApi.getAiPredictFeature(
          startDate: time[0],
          endDate: time[1],
          queryCondition: state.queryCondition.value));
      state.typeCount.makeColors();
    } catch (e) {
      print("AI预警饼图加载失败:$e");
    }
  }

  void lastPage() {
    if (aiWarningListPage.value == 1) {
      showToast("已经是第一页");
    } else {
      aiWarningListPage--;
      getList(getTime(state.dateType.value));
    }
  }

  void nextPage() {
    if (aiWarningListPage.value > state.aiWarningListTotalPage.value) {
      aiWarningListPage.value = state.aiWarningListTotalPage.value;
    } else if (aiWarningListPage.value == state.aiWarningListTotalPage.value) {
      showToast("已经是最后一页");
    } else {
      aiWarningListPage++;
      getList(getTime(state.dateType.value));
    }
  }

  Future<void> getList(List<String> time) async {
    try {
      AiWarningitemBean? aiWarningList = await AiWarningApi.getList(
          page: aiWarningListPage.value,
          startTime: time[0],
          endTime: time[1],
          queryCondition: state.queryCondition.value);
      state.aiWarningList.clear();
      state.aiWarningList.addAll(aiWarningList?.list ?? []);
      state.aiWarningListTotalPage.value = aiWarningList?.pages?.toInt() ?? 0;
      aiWarningListPage.value = aiWarningList?.pageNum?.toInt() ?? 0;
    } catch (e) {
      print("AI预警列表加载失败:$e");
    }
  }

  @override
  void onClose() {
    super.onClose();
    listener?.cancel();
  }
}
